<?php


namespace App\Http\Middleware;

use App\Exceptions\BusinessException;
use App\Models\MiniProgram;
use Closure;
use Illuminate\Http\Request;

class CheckMiniType
{
    public function handle(Request $request, Closure $next)
    {
        $uploadUrl = [
            '/api/images', '/api/imagesU', '/api/imagesW'
        ];

        if (in_array($request->getPathInfo(), $uploadUrl)) {
            return $next($request);
        }

        if ($request->is('api/wechat_notify/*')) {
            return $next($request);
        }

        $type = $request->header('X-MINI-TYPE');
        if (!$type) {
            throw new BusinessException('小程序标识不能为空', 40000);
        }

        $record = MiniProgram::where('slug', '=', $type)->first();

        if (!$record) {
            throw new BusinessException('小程序标识错误', 40000);
        }

        if (!$record->status) {
            throw new BusinessException('小程序已被禁用', 40000);
        }

        return $next($request);
    }
}
